﻿namespace Digitalmes.Application.Sys.Users.Commands;

/// <summary>
/// 创建用户命令。
/// </summary>
public record CreateUserCommand(SysUserDto User) : IRequest<IResult<bool>>;

internal sealed class CreateUserCommandHandler(IRepository<SysUser> repo) : IRequestHandler<CreateUserCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
    {
        // 检查账号名是否已存在。
        if (await repo.IsAnyAsync(m => m.Username == request.User.Username, cancellationToken))
        {
            return Result.Failure("账号已存在");
        }

        var user = request.User.Adapt<SysUser>();
        // 对明文密码进行MD5处理
        user.Password = CryptoUtils.MDString("admin1234"); // 默认初始密码
        var ok = await repo.InsertAsync(user, cancellationToken);
        return Result.From(ok);
    }
}
